-- element_altar
-- Created by chengb Jul/10/2015
-- 成就：元素圣坛圆满

-- 内部函数声明
local whenSubmitElement;

-- 关注元素圣坛圆满的事件
EventMgr.register("achievements/element_altar", event.SUBMIT_ELEM, function(args)
    whenSubmitElement(args);
end);

-- 元素圣坛圆满的事件回调
whenSubmitElement = function(args)
    local isFinal = args.isFinal;
    
    if not isFinal then
        -- 尚未圆满
        return;
    end
    
    local info    = args.info;
    local applyKey = table.keys(info["apply"])[1];

    -- 玩家不在迷宫中
    if not DungeonM.isInDungeon() then
        return;
    end

    -- 获取当前所在的迷宫编号
    local dungeonId = DungeonM.getDungeonId();

    -- 遍历所有的子规则
    local ids = AchievementM.getIdsByRule("element_altar");

    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == AchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        if not AchievementM.isBelongTo(id, dungeonId) then
            -- 不是该迷宫的成就
            return false;
        end

        -- 判断是否是需求的组合
        local config = AchievementM.query(id);
        local ruleArg = config["rule_arg"];
        if type(ruleArg) == 'table' then
            if type(ruleArg["id"]) == 'number' and 
               ruleArg["id"] ~= info["id"] then
                return false;
            end

            if type(ruleArg["id"]) == 'table' and 
               table.indexOf(ruleArg["id"], info["id"]) == -1 then
                return false;
            end
            
            if type(ruleArg["apply_key"]) == 'string' and 
               ruleArg["apply_key"] ~= applyKey then
                return false;
            end
        end

        return true;
    end

    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            AchievementM.tryComplete(id, 1);
        end
    end
end

return {

};